<template>
  <div class="device-params-panel">
    <div class="panel-header">
      <div class="left-section">
        <h2>设备参数</h2>
      </div>
      <div class="right-section">
        <el-button type="primary" @click="submitForm" :loading="submitting">
          保存设置
        </el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="info" @click="showHistoryDialog">
          <el-icon><Clock /></el-icon>
          历史记录
        </el-button>
        <el-button v-if="isFullscreen" type="primary" @click="exitFullscreen">
          <el-icon><Close /></el-icon>
          退出全屏
        </el-button>
      </div>
    </div>
    <div class="params-form">
      <el-form :model="form" label-position="left" label-width="180px">
        <!-- 系统参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>系统参数</span>
          </div>
          <el-form-item label="系统日期时间">
            <el-date-picker v-model="form.system_datetime" type="datetime" format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </div>

        <!-- 动力设备启停控制 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>动力设备启停控制</span>
          </div>
          <el-form-item label="动力设备启停控制">
            <div class="control-buttons">
              <el-button 
                type="success" 
                :class="{ 'active-button': form.power_plant_start_stop_control === 1 }"
                @mousedown="handlePowerControl(1)"
                @mouseup="handlePowerControl(0)"
                @mouseleave="handlePowerControl(0)"
              >
                启动
              </el-button>
              <el-button 
                type="danger" 
                :class="{ 'active-button': form.power_plant_start_stop_control === 2 }"
                @mousedown="handlePowerControl(2)"
                @mouseup="handlePowerControl(0)"
                @mouseleave="handlePowerControl(0)"
              >
                停止
              </el-button>
              <el-button 
                type="warning" 
                :class="{ 'active-button': form.power_plant_start_stop_control === 3 }"
                @mousedown="handlePowerControl(3)"
                @mouseup="handlePowerControl(0)"
                @mouseleave="handlePowerControl(0)"
              >
                复位
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 压力参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>压力参数</span>
          </div>
          <el-form-item label="油压 (Mpa)">
            <el-input-number v-model="form.oil_pressure" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="套压 (Mpa)">
            <el-input-number v-model="form.casing_pressure" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="回压 (Mpa)">
            <el-input-number v-model="form.return_pressure" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="井口油温 (°C)">
            <el-input-number v-model="form.well_oil_temperature" :precision="1" :step="0.1" />
          </el-form-item>
          <el-form-item label="井液比重 (0.1kg/m³)">
            <el-input-number v-model="form.fluid_specific_gravity" :precision="1" :step="0.1" />
          </el-form-item>
        </div>

        <!-- 动力设备参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>动力设备参数</span>
          </div>
          <el-form-item label="动力设备启动报警延时时间 (min)">
            <el-input-number v-model="form.power_equipment_start_alarm_delay_time" :min="0" />
          </el-form-item>
        </div>

        <!-- 电机参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>电机参数</span>
          </div>
          <el-form-item label="电机运行模式">
            <div class="control-buttons">
              <el-button 
                :type="form.motor_operating_mode === 0 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.motor_operating_mode === 0 }"
                @click="form.motor_operating_mode = 0; handleMotorModeUpdate('motor_operating_mode', 0)"
              >
                工频
              </el-button>
              <el-button 
                :type="form.motor_operating_mode === 1 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.motor_operating_mode === 1 }"
                @click="form.motor_operating_mode = 1; handleMotorModeUpdate('motor_operating_mode', 1)"
              >
                变频
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="频率控制方式">
            <el-input-number v-model="form.frequency_control_system" />
          </el-form-item>
          <el-form-item label="电机运行频率下限 (Hz)">
            <el-input-number v-model="form.lower_limit_of_motor_operating_frequency" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="允许电机最大电流 (0.01A)">
            <el-input-number v-model="form.maximum_allowable_motor_current" :precision="2" :step="0.01" />
          </el-form-item>
        </div>

        <!-- 空抽控制参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>空抽控制参数</span>
          </div>
          <el-form-item label="空抽控制使能">
            <el-select v-model="form.the_air_exhaust_control_function_was_enabled">
              <el-option label="无空抽控制" :value="0" />
              <el-option label="有空抽控制" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="空抽停机时间 (min)">
            <el-input-number v-model="form.idle_down_time" :min="0" />
          </el-form-item>
          <el-form-item label="空抽停机时间手/智动设定">
            <el-select v-model="form.idle_down_time_manual_mental_setting">
              <el-option label="手动控制" :value="0" />
              <el-option label="智能控制" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="空抽停机时摆动运行">
            <el-select v-model="form.swing_operation_when_empty_pumping_stops">
              <el-option label="停机" :value="0" />
              <el-option label="摆动运行" :value="1" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 间抽控制参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>间抽控制参数</span>
          </div>
          <el-form-item label="间抽控制使能">
            <el-select v-model="form.the_intermittent_control_is_enabled">
              <el-option label="无间抽" :value="0" />
              <el-option label="间抽使能" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="间抽开机时间">
            <el-time-picker v-model="form.time_to_switch_on" format="HH:mm:ss" />
          </el-form-item>
          <el-form-item label="间抽停机时间">
            <el-time-picker v-model="form.alternate_downtime" format="HH:mm:ss" />
          </el-form-item>
        </div>

        <!-- 自启动参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>自启动参数</span>
          </div>
          <el-form-item label="断电恢复自启动使能">
            <el-select v-model="form.enable_automatic_startup_after_power_failure_recovery">
              <el-option label="无自启动" :value="0" />
              <el-option label="有自启动" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="允许断电恢复自启动时间 (min)">
            <el-input-number v-model="form.allow_power_off_recovery_from_start_time" :min="0" />
          </el-form-item>
        </div>

        <!-- 冲次参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>冲次参数</span>
          </div>
          <el-form-item label="手动冲次/自动冲次">
            <el-select v-model="form.manual_sprint_automatic_sprint">
              <el-option label="手动控制" :value="0" />
              <el-option label="自动调速" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="手动冲次设定值 (0.01次/min)">
            <el-input-number v-model="form.manual_stroke_set_value" :precision="2" :step="0.01" />
          </el-form-item>
          <el-form-item label="自动调速泵效设定值 (0.01)">
            <el-input-number v-model="form.automatic_speed_pump_efficiency_set_value" :precision="2" :step="0.01" />
          </el-form-item>
        </div>

        <!-- 煤层气控制参数 -->
        <div class="params-group">
          <div class="group-title">
            <div class="title-line"></div>
            <span>煤层气控制</span>
          </div>
          <el-form-item label="设定液面 (m)">
            <el-input-number v-model="form.a1" :precision="2" :step="0.1" />
          </el-form-item>
          <el-form-item label="设定流压 (0.001Mpa)">
            <el-input-number v-model="form.a2" :precision="3" :step="0.001" />
          </el-form-item>
          <el-form-item label="设定流压下降率">
            <el-input-number v-model="form.a3" :precision="2" :step="0.01" />
          </el-form-item>
          <el-form-item label="生产控制模式">
            <div class="control-buttons">
              <el-button 
                :type="form.a4 === 2 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a4 === 2 }"
                @click="form.a4 = 2; handleGasControlUpdate('a4', 2)"
              >
                降流压
              </el-button>
              <el-button 
                :type="form.a4 === 3 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a4 === 3 }"
                @click="form.a4 = 3; handleGasControlUpdate('a4', 3)"
              >
                稳流压
              </el-button>
              <el-button 
                :type="form.a4 === 4 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a4 === 4 }"
                @click="form.a4 = 4; handleGasControlUpdate('a4', 4)"
              >
                稳套压
              </el-button>
              <el-button 
                :type="form.a4 === 5 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a4 === 5 }"
                @click="form.a4 = 5; handleGasControlUpdate('a4', 5)"
              >
                稳气量
              </el-button>
              <el-button 
                :type="form.a4 === 6 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a4 === 6 }"
                @click="form.a4 = 6; handleGasControlUpdate('a4', 6)"
              >
                稳液面
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="控制方式">
            <div class="control-buttons">
              <el-button 
                :type="form.a5 === 1 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a5 === 1 }"
                @click="form.a5 = 1; handleGasControlUpdate('a5', 1)"
              >
                手动
              </el-button>
              <el-button 
                :type="form.a5 === 8 ? 'primary' : 'default'" 
                :class="{ 'active-button': form.a5 === 8 }"
                @click="form.a5 = 8; handleGasControlUpdate('a5', 8)"
              >
                智能
              </el-button>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useDeviceStore } from '@/stores/device';
import { ElMessage } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import dayjs from 'dayjs';

const deviceStore = useDeviceStore();
const { currentDevice } = storeToRefs(deviceStore);

const formRef = ref(null);
const loading = ref(false);
const submitting = ref(false);
const isFullscreen = ref(false);

// 上次请求时间，用于节流
let lastFetchTime = null;

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

// 退出全屏
const exitFullscreen = async () => {
  try {
    await document.exitFullscreen();
  } catch (err) {
    ElMessage.error('退出全屏失败');
  }
};

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange);
});

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
});

const form = reactive({
  system_datetime: '',
  oil_pressure: 0,
  casing_pressure: 0,
  return_pressure: 0,
  well_oil_temperature: 0,
  fluid_specific_gravity: 0,
  power_plant_start_stop_control: 0,
  power_equipment_start_alarm_delay_time: 0,
  motor_operating_mode: 0,
  frequency_control_system: 0,
  lower_limit_of_motor_operating_frequency: 0,
  maximum_allowable_motor_current: 0,
  the_air_exhaust_control_function_was_enabled: 0,
  idle_down_time: 0,
  idle_down_time_manual_mental_setting: 0,
  swing_operation_when_empty_pumping_stops: 0,
  the_intermittent_control_is_enabled: 0,
  time_to_switch_on: null,
  alternate_downtime: null,
  enable_automatic_startup_after_power_failure_recovery: 0,
  allow_power_off_recovery_from_start_time: 0,
  manual_sprint_automatic_sprint: 0,
  manual_stroke_set_value: 0,
  automatic_speed_pump_efficiency_set_value: 0,
  // 煤层气控制参数
  a1: 0, // 设定液面
  a2: 0, // 设定流压
  a3: 0, // 设定流压下降率
  a4: 2, // 生产控制模式，默认为降流压
  a5: 1  // 控制方式，默认为手动
});

// 存储初始表单值，用于比较哪些字段被修改
const originalForm = ref({});

// 获取设备参数
const fetchDeviceParams = async () => {
  if (!currentDevice.value) return;
  
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    // 使用设备的 ID 作为 deviceId
    const deviceId = currentDevice.value.id.toString();
    
    // 添加节流，避免短时间内重复请求
const now = Date.now();
if (lastFetchTime && now - lastFetchTime < 60000) {
  console.log('请求过于频繁，使用缓存数据');
  loading.value = false;
  return;
}
lastFetchTime = now;

const response = await fetch(`https://penglink.pcwxcn.top/api/oil/data/${deviceId}?page=1&page_size=20`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
      // 移除credentials:'include'选项以解决CORS跨域问题
    });

    if (!response.ok) {
      throw new Error('获取参数失败');
    }

    const result = await response.json();
    if (result.code === 200 && result.data?.list?.length > 0) {
      const data = result.data.list[0];      // 确保所有数值类型的字段都被转换为数字
      const formData = {
        system_datetime: data.system_time && data.system_date ? 
          `${data.system_date} ${data.system_time}` : '',
        oil_pressure: Number(data.oil_pressure || 0),
        casing_pressure: Number(data.casing_pressure || 0),
        return_pressure: Number(data.return_pressure || 0),
        well_oil_temperature: Number(data.well_oil_temperature || 0),
        fluid_specific_gravity: Number(data.fluid_specific_gravity || 0),
        power_plant_start_stop_control: Number(data.power_plant_start_stop_control || 0),
        power_equipment_start_alarm_delay_time: Number(data.power_equipment_start_alarm_delay_time || 0),
        motor_operating_mode: Number(data.motor_operating_mode || 0),
        frequency_control_system: Number(data.frequency_control_system || 0),
        lower_limit_of_motor_operating_frequency: Number(data.lower_limit_of_motor_operating_frequency || 0),
        maximum_allowable_motor_current: Number(data.maximum_allowable_motor_current || 0),
        the_air_exhaust_control_function_was_enabled: Number(data.the_air_exhaust_control_function_was_enabled || 0),
        idle_down_time: Number(data.idle_down_time || 0),
        idle_down_time_manual_mental_setting: Number(data.idle_down_time_manual_mental_setting || 0),
        swing_operation_when_empty_pumping_stops: Number(data.swing_operation_when_empty_pumping_stops || 0),
        the_intermittent_control_is_enabled: Number(data.the_intermittent_control_is_enabled || 0),
        time_to_switch_on: data.time_to_switch_on ? new Date(`2000-01-01T${data.time_to_switch_on}`) : null,
        alternate_downtime: data.alternate_downtime ? new Date(`2000-01-01T${data.alternate_downtime}`) : null,
        enable_automatic_startup_after_power_failure_recovery: Number(data.enable_automatic_startup_after_power_failure_recovery || 0),
        allow_power_off_recovery_from_start_time: Number(data.allow_power_off_recovery_from_start_time || 0),
        manual_sprint_automatic_sprint: Number(data.manual_sprint_automatic_sprint || 0),
        manual_stroke_set_value: Number(data.manual_stroke_set_value || 0),
        automatic_speed_pump_efficiency_set_value: Number(data.automatic_speed_pump_efficiency_set_value || 0),
        // 煤层气控制参数
        a1: Number(data.a1 || 0),
        a2: Number(data.a2 || 0),
        a3: Number(data.a3 || 0),
        a4: Number(data.a4 || 2),
        a5: Number(data.a5 || 1)
      };
      
      // 保存原始表单值，用于后续比较
      originalForm.value = JSON.parse(JSON.stringify(formData));
      
      // 更新表单数据
      Object.assign(form, formData);
    }
  } catch (error) {
    // console.error('获取设备参数失败:', error);
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};

// 处理煤层气控制参数更新
const handleGasControlUpdate = async (paramName, value) => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备')
    return
  }

  try {
    const token = localStorage.getItem('token')
    // 使用设备的 ID 作为 deviceId
    const deviceId = currentDevice.value.id.toString()
    
    const submitData = {
      id: 1, // 假设 id=1 是正确的，如果后端需要特定 id，请修改
      [paramName]: String(value ?? '') // 使用正确的参数名
    }

    // console.log('发送煤层气控制参数更新:', submitData)
    
    const response = await fetch(`https://penglink.pcwxcn.top/api/oil/currency/data/${deviceId}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      throw new Error('更新参数失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('参数更新成功')
      // 更新成功后，同步更新 originalForm 的值，防止保存时误判为修改
      if (originalForm.value) {
        originalForm.value[paramName] = value;
      }
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error) {
    // console.error('更新煤层气控制参数失败:', error)
    ElMessage.error(error.message)
    // 更新失败时，恢复表单项的值到原始值
    if (originalForm.value && originalForm.value.hasOwnProperty(paramName)) {
      form[paramName] = originalForm.value[paramName];
    }
  }
}

// 处理电机运行模式更新
const handleMotorModeUpdate = async (paramName, value) => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备')
    return
  }

  try {
    const token = localStorage.getItem('token')
    // 使用设备的 ID 作为 deviceId
    const deviceId = currentDevice.value.id.toString()
    
    const submitData = {
      id: 1, // 假设 id=1 是正确的
      [paramName]: String(value ?? '') // 使用正确的参数名 'motor_operating_mode'
    }
    
    const response = await fetch(`https://penglink.pcwxcn.top/api/oil/currency/data/${deviceId}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      throw new Error('更新参数失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('参数更新成功')
      // 更新成功后，同步更新 originalForm 的值
      if (originalForm.value) {
        originalForm.value[paramName] = value;
      }
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error) {
    // console.error('更新电机运行模式失败:', error)
    ElMessage.error(error.message)
    // 更新失败时，恢复表单项的值到原始值
    if (originalForm.value && originalForm.value.hasOwnProperty(paramName)) {
      form[paramName] = originalForm.value[paramName];
    }
  }
}

// 处理动力设备启停控制
const handlePowerControl = async (value) => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备')
    return
  }

  // 仅在按下按钮时发送请求
  if (value === 0) return;

  try {
    const token = localStorage.getItem('token')
    // 使用设备的 ID 作为 deviceId
    const deviceId = currentDevice.value.id.toString()
    
    const submitData = {
      id: 1,
      power_plant_start_stop_control: String(value || '0')
    }
    
    const response = await fetch(`https://penglink.pcwxcn.top/api/oil/currency/data/${deviceId}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      throw new Error('更新参数失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('参数更新成功')
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 提交表单
const submitForm = async () => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备');
    return;
  }

  submitting.value = true;
  try {
    const token = localStorage.getItem('token');
    // 使用设备的 ID 作为 deviceId
    const deviceId = currentDevice.value.id.toString();

    // 找出被修改的字段
    const submitData = { id: 1 }; // 初始化 submitData
    const originalDateTime = originalForm.value.system_datetime
    const currentDateTime = form.system_datetime
    if (originalDateTime !== currentDateTime) {
      submitData.system_time = currentDateTime ? dayjs(currentDateTime).format('YYYY-MM-DD HH:mm:ss') : ''
      submitData.system_date = currentDateTime ? dayjs(currentDateTime).format('YYYY-MM-DD') : ''
    }
    
    // 检查其他字段是否有变化
    const fieldsToCheck = [
      'oil_pressure', 'casing_pressure', 'return_pressure', 'well_oil_temperature',
      'fluid_specific_gravity', 'power_plant_start_stop_control', 'power_equipment_start_alarm_delay_time',
      'motor_operating_mode', 'frequency_control_system', 'lower_limit_of_motor_operating_frequency',
      'maximum_allowable_motor_current', 'the_air_exhaust_control_function_was_enabled',
      'idle_down_time', 'idle_down_time_manual_mental_setting', 'swing_operation_when_empty_pumping_stops',
      'the_intermittent_control_is_enabled', 'enable_automatic_startup_after_power_failure_recovery',
      'allow_power_off_recovery_from_start_time', 'manual_sprint_automatic_sprint',
      'manual_stroke_set_value', 'automatic_speed_pump_efficiency_set_value',
      'a1', 'a2', 'a3', 'a4', 'a5'
    ]
    
    fieldsToCheck.forEach(field => {
      if (originalForm.value[field] !== form[field]) {
        submitData[field] = String(form[field] || '0')
      }
    })
    
    // 检查时间字段
    if (originalForm.value.time_to_switch_on !== form.time_to_switch_on) {
      submitData.time_to_switch_on = form.time_to_switch_on && dayjs(form.time_to_switch_on).isValid() ? dayjs(form.time_to_switch_on).format('HH:mm:ss') : ''
    }
    
    if (originalForm.value.alternate_downtime !== form.alternate_downtime) {
      submitData.alternate_downtime = form.alternate_downtime && dayjs(form.alternate_downtime).isValid() ? dayjs(form.alternate_downtime).format('HH:mm:ss') : ''
    }
    
    // 如果没有修改任何字段，则提示用户
    if (Object.keys(submitData).length <= 1) { // 只有id字段
      ElMessage.info('没有修改任何参数，无需保存')
      submitting.value = false
      return
    }
    
    // console.log('提交修改的参数:', submitData)

    // 不需要手动发送预检请求，浏览器会自动处理
    // 直接使用代理路径发送PUT请求

    const response = await fetch(`https://penglink.pcwxcn.top/api/oil/currency/data/${deviceId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      const errorData = await response.json().catch(() => null)
      throw new Error(errorData?.message || `保存失败 (${response.status})`)
    }

    const result = await response.text()
    // console.log('保存结果:', result)
    
    ElMessage.success('保存成功')
    // 刷新数据
    fetchDeviceParams()
  } catch (error) {
    // console.error('保存参数失败:', error)
    ElMessage.error(error.message || '保存失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  fetchDeviceParams()
}

// 监听设备变化
watch(currentDevice, (newDevice) => {
  if (newDevice) {
    fetchDeviceParams()
  }
})

// 生命周期钩子
onMounted(() => {
  if (currentDevice.value) {
    fetchDeviceParams()
  }
})
</script>

<style scoped>
.device-params-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-bottom: 1px solid #EBEEF5;
}

.panel-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-button) {
  padding: 4px 12px;
  height: 24px;
  font-size: 12px;
}

:deep(.el-icon) {
  font-size: 12px;
}

.params-form {
  padding: 12px;
  background: linear-gradient(180deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0) 100%);
}

.params-form {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px;
}

.control-buttons {
  display: flex;
  gap: 10px;
}

.active-button {
  filter: brightness(1.2);
  transform: scale(0.98);
}

.params-group {
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
}

.group-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  position: relative;
}

.title-line {
  width: 4px;
  height: 16px;
  background: linear-gradient(180deg, #409EFF, #0052D9);
  border-radius: 2px;
  margin-right: 8px;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.group-title span {
  font-size: 14px;
  font-weight: 500;
  color: #1f2f3d;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-size: 13px;
  color: #606266;
}

:deep(.el-input-number) {
  width: 160px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 16px 0;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-button--primary) {
  background: linear-gradient(180deg, #409EFF 0%, #0052D9 100%);
  border: none;
  padding: 8px 24px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

:deep(.el-button--primary:active) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--default) {
  border: 1px solid #dcdfe6;
  padding: 8px 24px;
  height: 36px;
  transition: all 0.3s ease;
}

:deep(.el-button--default:hover) {
  border-color: #409EFF;
  color: #409EFF;
  transform: translateY(-1px);
}

:deep(.el-button--default:active) {
  transform: translateY(0);
}
}
</style>
